package com.es;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;
import java.util.Properties;

/**
 * 用来解析配置文件的工具类
 */
public class JDBCConfigParser {

    /**
     * @param configFile 配置文件的名字
     * @return
     */
    public static HashMap<String, Properties> parse(String configFile){

        HashMap<String, Properties> configsMap = new HashMap<>();

        //
        SAXReader saxReader = new SAXReader();
        //读取指定的配置文件
        try {
            Document document = saxReader.read(JDBCConfigParser.class.getClassLoader().getResourceAsStream(configFile));
            //获取根元素
            Element rootElement = document.getRootElement();
            //读取所有的环境配置
            Element envsElement = rootElement.element("environments");
            //读取所有的环境
            List<Element> elements = envsElement.elements("environment");
            for(Element element: elements){
                //id
                String envId = element.attributeValue("id").trim();
                //
                String driverClassName = element.elementText("driverClassName");
                String user = element.elementText("user");
                String password = element.elementText("password");
                String url = element.elementText("url");

                Properties properties = new Properties();
                properties.setProperty("driverClassName",driverClassName);
                properties.setProperty("url", url);
                properties.setProperty("user", user);
                properties.setProperty("password", password);

                configsMap.put(envId, properties);
            }


        } catch (DocumentException e) {
            e.printStackTrace();
        }

        return configsMap;
    }

}
